﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Model;
using HtmlAgilityPack;
using Model.Msg;
using System.Xml.Linq;
using DMTroube_ZeKer;
using DMTroube_ZeKer.View;
using System.Linq.Expressions;
using Microsoft.Extensions.Caching.Memory;
using static DMTroube_ZeKer.View.GiftPage;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Controller
{
    public class InfoAnalysis
    {
        private static HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
        //礼物缓存
        private static IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
        //默认礼物缓存时间15秒
        static int lwCachetime = 15;
        public static void init(string resultJson, Action<object?, ResultAnalysisInfo>? action1, Action<object?, ResultAnalysisInfo>? action2, Action<object?, ResultAnalysisInfo>? action3)
        {
            if (resultJson != null && resultJson != "null")
            {
                ResultWebMsg? result = JsonSerializer.Deserialize<ResultWebMsg>(resultJson);
                if (result != null)
                {
                    if (result.Type == "info")
                    {
                        ResultAnalysisInfo resultAnalysis = RightMsg(result.Html);
                        if (resultAnalysis.Type == 0)
                        {
                            action1?.Invoke(null, resultAnalysis);
                        }
                        else
                        {
                            action2?.Invoke(null, resultAnalysis);
                        }
                    }
                    else if (result.Type == "liwu")
                    {
                        ResultAnalysisInfo resultAnalysis = LeftGit(result.Html);
                        action2?.Invoke(null, resultAnalysis);
                    }
                    else if (result.Type == "likeinfo")
                    {
                        ResultAnalysisInfo resultAnalysis = RightBottomMsg(result.Html);
                        action3?.Invoke(null, resultAnalysis);
                    }
                }
            }
        }

        private static ResultAnalysisInfo RightBottomMsg(string? html)
        {
            ResultAnalysisInfo resultAnalysis = new ResultAnalysisInfo();
            if (string.IsNullOrWhiteSpace(html) || html.StartsWith("null")) { return resultAnalysis; }
            htmlDocument.LoadHtml(html);
            var nameNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='u2QdU6ht']");
            var msgNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='WsJsvMP9']");
            resultAnalysis.UserName = nameNode != null ? nameNode.InnerText : "未知";
            resultAnalysis.Content = msgNode != null ? msgNode.InnerText : "未知";
            return resultAnalysis;
        }

        private static ResultAnalysisInfo LeftGit(string? html)
        {
            ResultAnalysisInfo resultAnalysis = new ResultAnalysisInfo();
            if (string.IsNullOrWhiteSpace(html) || html.StartsWith("null")) { return resultAnalysis; }
            htmlDocument.LoadHtml(html);
            var nameNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='sTl5e5sP']");
            var gifNameNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='H5qf9eIj']");
            var gifUrlNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='DHiwJa_2']");
            var gifNumNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='dnmQgQio']");
            string name, gifName, gifUrl; int gifNum = 0;

            //昵称
            name = nameNode != null ? nameNode.InnerText : "未知";
            //礼物名称
            gifName = gifNameNode != null ? gifNameNode.InnerText : "未知";
            //礼物图片链接
            gifUrl = gifUrlNode != null ? gifUrlNode.InnerText : "未知";
            //礼物数量
            gifNum = gifNumNode != null ? int.Parse(gifNumNode.InnerText) : 1;
            resultAnalysis.UserName = name;
            resultAnalysis.Gift = gifName;
            resultAnalysis.GiftUrl = gifUrl;
            resultAnalysis.GiftNum = gifNum;

            var cacheNum = _cache.Get(name.Trim() + "_" + gifName.Trim());
            if (cacheNum != null)
            {
                int tempNum = (int)cacheNum;
                if (tempNum < gifNum)
                    resultAnalysis.GiftNum = gifNum - tempNum;
            }
            _cache.Set(name.Trim() + "_" + gifName.Trim(), gifNum, new TimeSpan(0, 0, lwCachetime));
            return resultAnalysis;
        }

        private static ResultAnalysisInfo RightMsg(string? html)
        {
            ResultAnalysisInfo resultAnalysis = new ResultAnalysisInfo();
            if (string.IsNullOrWhiteSpace(html) || html.StartsWith("null")) { return resultAnalysis; }
            htmlDocument.LoadHtml(html);
            var imgNode = htmlDocument.DocumentNode.SelectSingleNode("//img");
            var nameNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='u2QdU6ht']");
            var contentTextNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='WsJsvMP9']");
            var contentImgNode = htmlDocument.DocumentNode.SelectSingleNode("//img[@class='DyNQfBip']");
            var contentNumNode = htmlDocument.DocumentNode.SelectSingleNode("//span[@class='tbZ6dkVE']");
            var tagNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='Zai1DjqS']");
            int level = 0; string name = ""; string contentText = ""; int giftNum = 0; string giftName = ""; string tag = "无";

            #region 等级
            string levelSrc = imgNode != null ? imgNode.Attributes["src"] != null ? imgNode.Attributes["src"].Value : "未知" : "0";
            if (levelSrc.Contains("level_v1_"))
            {
                string[] levelInfos = levelSrc.Replace("level_v1_", "|").Split("|");
                string levelinfo = levelInfos.Length > 1 ? levelInfos[1].Substring(0, 2) : "0";
                level = levelinfo.Contains(".") ? Convert.ToInt16(levelinfo.Replace(".", "")) : Convert.ToInt16(levelinfo);
            }
            #endregion

            //昵称
            name = nameNode != null ? nameNode.InnerText.Trim().TrimEnd('：') : "未知";
            //评论内容 
            if (contentTextNode != null)
            {
                foreach (var item in contentTextNode.ChildNodes)
                {
                    if (item.Attributes["class"].Value?.Trim() == "webcast-chatroom___content-with-emoji-text")
                    {
                        contentText += item.InnerText;
                    }
                    else if (item.Attributes["class"].Value.Trim() == "webcast-chatroom___content-with-emoji-emoji")
                    {
                        contentText += item.InnerHtml.Replace("'", "\"");
                    }
                    else
                    {
                        contentText += "[未知内容]";
                    }
                }
            }
            else
            {
                contentText = "未知";
            }

            //礼物数量
            giftNum = contentNumNode != null ? Convert.ToInt16(contentNumNode.InnerText.Replace("&nbsp;×&nbsp;", "")) : giftNum;
            //粉丝灯牌
            tag = tagNode != null ? tagNode.InnerText : "无";

            if (contentImgNode != null)
            {
                resultAnalysis.Type = 1;

                string gitsrc = contentImgNode.Attributes["src"].Value;
                resultAnalysis.GiftUrl = gitsrc;
                string[] srcKeys = gitsrc.Split("/");
                string srcKey = srcKeys[srcKeys.Length - 1].Split(".")[0];
                if (Main.lwlist.Any(n => n.src.Contains(srcKey)))
                {
                    giftName = Main.lwlist.Where(n => n.src.Contains(srcKey)).Select(n => n.name).First();
                }
                else
                {
                    GiftPage.LW lW = new GiftPage.LW();
                    lW.name = "未知";
                    lW.price = "未知";
                    lW.src = gitsrc;
                    Main.lwlist.Add(lW);
                }
                var cacheNum = _cache.Get(name.Trim() + "_" + giftName.Trim());
                if (cacheNum != null)
                {
                    int tempNum = (int)cacheNum;
                    _cache.Remove(name.Trim() + "_" + giftName.Trim());
                    if (tempNum < giftNum)
                    {
                        resultAnalysis.GiftNum = giftNum - tempNum;
                    }
                    else
                    {
                        giftNum = 0;
                    }
                }
                name += "(消息区)";
            }
            resultAnalysis.Level = level;
            resultAnalysis.FanGroup = tag;
            resultAnalysis.UserName = name;
            resultAnalysis.GiftNum = giftNum;
            resultAnalysis.Gift = giftName;
            resultAnalysis.Content = contentText;
            return resultAnalysis;
        }
    }
}
